define(['../common/common', '../common/pathCompute', 'ztree', 'text!../../pages/dataBase/costService.html', 'text!../../pages/dataBase/costServiceAdd.html'], function($, pathfn, ztree, costServiceHtml, costServiceAddHtml) {
      var interface = pathfn.interface,
        tableHeight = $(window).height() - $('#budget-header').height() - $('.layui-footer').height() - 80;
      var costService = function(popId) {
        if(popId){
          $('#' + popId.id).html(costServiceHtml);
          $('.projectHideBtn').hide(0);
        } else{
          $('.page-content').html(costServiceHtml); 
          var addCostCodeHtml = $(costServiceAddHtml)[0];
        }
        layui.use(['table', 'form', 'laypage'], function() {
            var table = layui.table,
              form = layui.form,
              laypage = layui.laypage;
            var init = function() {
              ztreeOperate.ztreeInit();
              bindEvents();
            },
            ztreeOperate = {
              setting: {
                async: {
                  enable: true,
                  url: interface.typeInfo,
                  autoParam: ["listCode='COST_CODE'", "node=='root'"]
                },
                data: {
                  key: {
                    title: "",
                    name: 'text'
                  }
                },
                callback: {
                  onAsyncSuccess: function(event, treeId, treeNode, msg) {
                    var treeObj = $.fn.zTree.getZTreeObj("tree-list"),
                      //获取ztree 所有节点
                      getNodes = treeObj.getNodes();
                    //获取ztree 第一个节点
                    treeObj.selectNode(getNodes[0]);
                    //給第一个节点触发点击事件，显示右边table
                    ztreeOperate.setting.callback.onClick('click', 'tree-list', getNodes);
                    //展开ztree
                    treeObj.expandAll(true);
                    $('.content-loading').remove();
                  },
                  onClick: function(even, treeId, treeNode) {
                    var treeNode = treeNode[0] || treeNode;
                    if(!popId){
                      !treeNode.leaf > 0 ? $('.add-costCode').slideUp(100) : $('.add-costCode').slideDown(100);
                    }                    
                    tableOperate.tableInit(even, treeId, treeNode);
                    //layer.closeAll();
                  }
                }
              },
              ztreeInit: function() { //加载左侧菜单树
                $.fn.zTree.init($("#tree-list"), this.setting);
              }
            },
            tableOperate = {
              tableInitObj: function() {
                if(popId){
                  var colsHeight = [
                      //{checkbox: true},
                      {field: 'no',title: '序号',width: 80,sort: true,align: 'center'}, 
                      {field: 'code',title: '编码',width: 200,sort: true}, 
                      {field: 'type',title: '类别',width: 80,sort: true}, 
                      {field: 'name',title: '名称',width: 200}, 
                      {field: 'unit',title: '单位',width: 80,sort: true}, 
                      {field: 'tax_Price',title: '含税单价',width: 120}, 
                      {field: 'notax_Price',title: '不含税单价',width: 120,sort: true}, 
                      {field: 'amount',title: '数量',width: 120}, 
                      {field: 'tax_Single_SumPrice',title: '含税合价',width: 120,sort: true}, 
                      {field: 'single_SumPrice',title: '不含税合价',width: 120}
                  ],
                  objUrl = interface.ycaTotalInfo,
                  tableH = tableHeight - 100
                }else{
                  var colsHeight = [ //标题栏
                    //{checkbox: true},
                    {field: 'no',title: '序号',width: 100,sort: true,align: 'center'}, 
                    {field: 'lookvalueName',title: '费用名称',width: 280,sort: true}, 
                    {field: 'lookvalueCode',title: '费用代码',width: 280}, 
                    {field: 'remark',width: 280,style: 'cursor: pointer;',title: '备注'}, 
                    {field: 'enableFlag',width: 100,templet: '#isFlag',style: 'cursor: pointer;',title: '是否有效',align: 'center'}, 
                    {field: 'caozuo',fixed: 'right',title: '操作',width: 160,align: 'center',toolbar: '#barDemo'}
                  ],
                  objUrl = interface.valueInfo,
                  tableH = tableHeight
                };
                var obj = {
                  id: 'const-table',
                  elem: '#const-table', //指定原始表格元素选择器（推荐id选择器）
                  height: tableH, //容器高度
                  cols: [colsHeight],
                  url: objUrl,
                  method: 'get',
                  page: true, //开启分页
                  initSort: {
                    field: 'lookvalueId', //排序字段，对应 cols 设定的各字段名
                    type: 'desc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
                  },
                  limit: 30, //默认采用60
                  loading: true
                }
                return obj;
              },
              tableInit: function(even, treeId, treeNode) {
                var _this = this,
                  where = {
                  lookTypeId: treeNode && treeNode.id !== '0' && treeNode.id || ''
                };
                if(popId){
                  where.bitProjectId = popId.bitProjectId;
                }
                var defaults = {
                  where: where,
                  done: function(res, curr, count) {
                    if(!popId){
                      _this.listEdit(_this.tableInitObj());
                    }                   
                  }
                };
                $.extend(true, defaults, _this.tableInitObj());
                table.render(defaults);
                _this.tableEdit();
              },
              tableEdit: function() {
                table.on('tool(costCodeEvent)', function(obj) {
                  var dataObj = obj.data;
                  if (obj.event === 'edit') {
                    var openObj = {
                      "content": $(addCostCodeHtml).html(),
                      "title": '修改',
                      "success": function(layero, index) {
                        layero.find("input[name='lookvalueCode']").val(dataObj.lookvalueCode).attr("readonly", "readonly");
                        layero.find("input[name='lookvalueName']").val(dataObj.lookvalueName).attr("readonly", "readonly");
                        layero.find("textarea[name='remark']").val(dataObj.remark);
                        layero.find("input[name='enableFlag'][value=" + dataObj.enableFlag + "]").attr("checked", true);
                        form.render();
                        form.on('submit(costCodeFilter)', function(data) {
                          var formData = data.field;
                          $.ajaxRequest({
                            url: interface.setValueInfo,
                            data: {
                              "cmd": 'edit',
                              "lookvalueId": dataObj.lookvalueId,
                              "lookvalueCode": formData.lookvalueCode,
                              "lookvalueName": formData.lookvalueName,
                              "remark": formData.remark,
                              "enableFlag": dataObj.enableFlag
                            },
                            successfn: function(data) {
                              if (data.code == 0) {
                                layer.msg("修改成功");
                                layer.close(index);
                              } else {
                                layer.msg(data.msg);
                              }
                              obj.update({
                                enableFlag: formData.enableFlag,
                                remark: formData.remark
                              });
                            },
                            errorfn: function(data) {
                              layer.msg(data);
                              layer.close(index);
                            }
                          })
                          return false;
                        });
                      }
                    }
                    layerOpenfn(openObj);
                  }
                });
                table.on('sort(costCodeEvent)', function(obj) {
                  var inputArr = $(this).parents('.layui-table-view').eq(0).find('.caozuo-vis').find("input[type='checkbox']");
                  for (var i = 0; i < inputArr.length; i++) {
                    var ischecked = inputArr.eq(i).prop('checked'),
                      field = $(inputArr[i]).data('field');
                    if (ischecked) {
                      $('td[data-field="' + field + '"],th[data-field="' + field + '"]').hide(0);
                    } else {
                      $('td[data-field="' + field + '"],th[data-field="' + field + '"]').show(0);
                    }
                  }
                })
              },
              listEdit: function($obj) {
                var elem = $obj.elem,
                  $caozuo = $(elem).next('.layui-table-view');
                if (!$caozuo.find('.caozuo-vis').length) {
                  pathfn._toggleVisInit($obj.cols, $obj.elem, function() {
                    form.render();
                  });
                } else {
                  var inputArr = $caozuo.find('.caozuo-vis').find("input[type='checkbox']");
                  for (var i = 0; i < inputArr.length; i++) {
                    var ischecked = inputArr.eq(i).prop('checked'),
                      field = $(inputArr[i]).data('field');
                    if (ischecked) {
                      $caozuo.find('td[data-field="' + field + '"],th[data-field="' + field + '"]').hide(0);
                    } else {
                      $caozuo.find('td[data-field="' + field + '"],th[data-field="' + field + '"]').show(0);
                    }
                  }
                }
              }
            },
            bindEvents = function() {
              $('.add-costCode').click(function() {
                var treeObj = $.fn.zTree.getZTreeObj("tree-list");
                var selectedNodes = treeObj.getSelectedNodes();
                var openObj = {
                  "content": $(addCostCodeHtml).html(),
                  "title": '新增',
                  "success": function(layero, index) {
                    form.render();
                    form.on('submit(costCodeFilter)', function(data) {
                      var formData = data.field;
                      $.ajaxRequest({
                        url: interface.setValueInfo,
                        data: {
                          "cmd": 'new',
                          "lookTypeId": selectedNodes[0].id,
                          "lookvalueCode": formData.lookvalueCode,
                          "lookvalueName": formData.lookvalueName,
                          "remark": formData.remark,
                          "enableFlag": formData.enableFlag
                        },
                        successfn: function(data) {
                          table.reload('const-table');
                        },
                        errorfn: function(data) {
                          table.reload('const-table');
                        }
                      })
                      layer.close(index);
                      return false;
                    });
                  }
                }
                layerOpenfn(openObj);
              })
            },
            layerOpenfn = function(openObj) {
              layer.open({
                type: openObj.type || 1,
                content: openObj.content || '',
                title: openObj.title || '',
                btn: ['确定', '取消'],
                area: openObj.area || '450px',
                skin: 'lay-padding',
                success: function(layero, index) {
                  openObj.success(layero, index) || (function() {})();
                },
                yes: function(index, layero) {
                  $('.costCodeFilter').trigger('click');
                },
                btn2: function(index, layero) {}
              });
            };
            init();
        })
      }
      return costService;
})